﻿using System;
using Csla;
using System.ComponentModel.DataAnnotations;
using BizControl.Resources;
using BizControl.DalLinq;
using BizControl.Library.BusinessObjects.People;
using BizControl.Library.BusinessObjects.Models;
using Csla.Data;
using System.Linq;
using System.Data.Linq;
using BizControl.Library.Security;

namespace BizControl.Library.BusinessObjects.BusinessRoles
{
  [Serializable()]
  public class BusinessRoleBO : BusinessBase<BusinessRoleBO>, ISupportEmptyValue
  {
    #region Business Methods

    private static readonly PropertyInfo<Guid> RoleIdProperty = RegisterProperty<Guid>(c => c.RoleId);
    [Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(ValidationErrors), ErrorMessageResourceName = @"BusinessRoleIdRequiredPropertyError")]
    public Guid RoleId
    {
      get { return GetProperty(RoleIdProperty); }
      private set { SetProperty(RoleIdProperty, value); }
    }

    private static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(c => c.Name);
    [Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(ValidationErrors), ErrorMessageResourceName = @"BusinessRoleNameRequiredPropertyError")]
    [StringLength(50, ErrorMessageResourceType = typeof(ValidationErrors), ErrorMessageResourceName = @"BusinessRoleNameLengthPropertyError")]
    [Display(ResourceType = typeof(PropertiesNames), Name = @"BusinessRoleNameProperty")]
    public string Name
    {
      get { return GetProperty(NameProperty); }
      set { SetProperty(NameProperty, value); }
    }

    private static readonly PropertyInfo<Guid?> ModelProperty = RegisterProperty<Guid?>(c => c.ModelId);
    [Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(ValidationErrors), ErrorMessageResourceName = @"ModelRequiredError")]
    [Display(ResourceType = typeof(PropertiesNames), Name = @"ModelIdProperty")]
    internal Guid? ModelId
    {
      get { return GetProperty(ModelProperty); }
      set { SetProperty(ModelProperty, value); }
    }

    #region Common properties

    private static readonly PropertyInfo<bool> IsDeletedFieldProperty = RegisterProperty<bool>(c => c.IsDeletedField, null, false);
    [Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(ValidationErrors), ErrorMessageResourceName = @"IsDeletedRequiredError")]
    [Display(ResourceType = typeof(PropertiesNames), Name = @"IsDeletedFieldProperty")]
    public bool IsDeletedField
    {
      get { return GetProperty(IsDeletedFieldProperty); }
      private set { SetProperty(IsDeletedFieldProperty, value); }
    }

    private static readonly PropertyInfo<PersonInfo> CreatedByProperty = RegisterProperty<PersonInfo>(c => c.CreatedBy);
    [Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(ValidationErrors), ErrorMessageResourceName = @"CreatedByRequiredPropertyError")]
    [Display(ResourceType = typeof(PropertiesNames), Name = @"CreatedByProperty")]
    public PersonInfo CreatedBy
    {
      get { return GetProperty(CreatedByProperty); }
      private set { SetProperty(CreatedByProperty, value); }
    }

    private static readonly PropertyInfo<DateTime> CreatedOnProperty = RegisterProperty<DateTime>(c => c.CreatedOn);
    [Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(ValidationErrors), ErrorMessageResourceName = @"CreatedOnRequiredPropertyError")]
    [Display(ResourceType = typeof(PropertiesNames), Name = @"CreatedOnProperty")]
    public DateTime CreatedOn
    {
      get { return GetProperty(CreatedOnProperty); }
      private set { SetProperty(CreatedOnProperty, value); }
    }

    private static readonly PropertyInfo<DateTime> LastChangedProperty = RegisterProperty<DateTime>(c => c.LastChanged);
    [Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(ValidationErrors), ErrorMessageResourceName = @"LastChangedRequiredPropertyError")]
    [Display(ResourceType = typeof(PropertiesNames), Name = @"LastChangedProperty")]
    public DateTime LastChanged
    {
      get { return GetProperty(LastChangedProperty); }
      private set { SetProperty(LastChangedProperty, value); }
    }

    private static readonly PropertyInfo<PersonInfo> LastChangedByProperty = RegisterProperty<PersonInfo>(c => c.LastChangedBy);
    [Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(ValidationErrors), ErrorMessageResourceName = @"LastChangedByRequiredPropertyError")]
    [Display(ResourceType = typeof(PropertiesNames), Name = @"LastChangedByProperty")]
    public PersonInfo LastChangedBy
    {
      get { return GetProperty(LastChangedByProperty); }
      private set { SetProperty(LastChangedByProperty, value); }
    }

    private static readonly PropertyInfo<byte[]> TimeStampProperty = RegisterProperty<byte[]>(c => c.TimeStamp);
    private byte[] TimeStamp
    {
      get { return GetProperty(TimeStampProperty); }
      set { SetProperty(TimeStampProperty, value); }
    }

    #endregion

    #region Children

    // PARTICIPANTS
    //private static readonly PropertyInfo<MarkPeople> PeopleProperty = RegisterProperty<MarkPeople>(p => p.People);
    //public MarkPeople People
    //{
    //  get
    //  {
    //    if (!(FieldManager.FieldExists(PeopleProperty)))
    //      LoadProperty(PeopleProperty, MarkPeople.NewMarkPeople(this));
    //    return GetProperty(PeopleProperty);
    //  }
    //}

    #endregion

    internal void LoadData(BusinessRole roleDB)
    {
      if (roleDB == null) return;
      RoleId = roleDB.RoleId;
      Name = roleDB.Name;
      ModelId = roleDB.Model;

      // Common properties
      CreatedBy = new PersonInfo(roleDB.CreatedByRef);
      LastChangedBy = new PersonInfo(roleDB.LastChangedByRef);

      CreatedOn = roleDB.CreatedOn;
      LastChanged = roleDB.LastChanged;

      IsDeletedField = roleDB.IsDeleted;
      TimeStamp = roleDB.TimeStamp.ToArray();
    }

    public override string ToString()
    {
      return RoleId.ToString();
    }

    #endregion

    #region Business Rules

    protected override void AddBusinessRules()
    {
      base.AddBusinessRules();
    }

    #endregion

    #region Authorization rules

    private static void AddObjectAuthorizationRules()
    {
      //BusinessRules.AddRule(typeof(BusinessRoleBO), new IsInRole(AuthorizationActions.CreateObject, "BusinessRoleBO.Create()"));
      //BusinessRules.AddRule(typeof(BusinessRoleBO), new IsInRole(AuthorizationActions.GetObject, "BusinessRoleBO.Get()"));
      //BusinessRules.AddRule(typeof(BusinessRoleBO), new IsInRole(AuthorizationActions.EditObject, "BusinessRoleBO.Edit()"));
      //BusinessRules.AddRule(typeof(BusinessRoleBO), new IsInRole(AuthorizationActions.DeleteObject, "BusinessRoleBO.Delete()"));
    }

    #endregion

    #region Data Access

    //[RunLocal]
    protected void DataPortal_Create(ModelBO model)
    {
      if (model == null) throw new ArgumentNullException(ExceptionsMessages.ModelNullReference);
      var currentUser = SecurityChecks.GetCurrentUser();
      using (BypassPropertyChecks)
      {
        RoleId = Guid.NewGuid();
        ModelId = model.ModelId;
        CreatedBy = new PersonInfo(currentUser);
        LastChangedBy = new PersonInfo(currentUser);
        CreatedOn = DateTime.Now;
      }
      base.DataPortal_Create();
    }

    private void DataPortal_Fetch(SingleCriteria<BusinessRoleBO, Guid> id)
    {
      using (var ctx = ContextManager<BusinessControl2DataContext>.GetManager(Database.BizControlDB))
      {
        var data = (from r in ctx.DataContext.BusinessRoles
                    where r.RoleId == id.Value && !r.IsDeleted
                    select r).SingleOrDefault();
        using (BypassPropertyChecks)
        {
          this.LoadData(data);
        }
        if (data != null)
        {
          //LoadProperty(PeopleProperty, RolePeople.GetMarkPeople(data.PersonMarks.ToArray(), this));
        }
      }
    }

    [Transactional(TransactionalTypes.TransactionScope)]
    protected override void DataPortal_Insert()
    {
      if (RoleId != Guid.Empty)
      {
        using (var ctx = ContextManager<BusinessControl2DataContext>.GetManager(Database.BizControlDB))
        {
          Binary lastTimeStamp = null;
          LastChanged = DateTime.Now;
          using (BypassPropertyChecks)
          {
            ctx.DataContext.AddBusinessRole(
              ModelId,
              RoleId,
              Name,
              IsDeletedField,
              CreatedBy == null || CreatedBy.IsEmpty() ? (Guid?)null : CreatedBy.Id,
              CreatedOn,
              LastChanged,
              LastChangedBy == null || LastChangedBy.IsEmpty() ? (Guid?)null : LastChangedBy.Id,
              ref lastTimeStamp);
            TimeStamp = lastTimeStamp.ToArray();
          }
          // update child objects
          FieldManager.UpdateChildren(this);
        }
      }
    }

    [Transactional(TransactionalTypes.TransactionScope)]
    protected override void DataPortal_Update()
    {
      if (RoleId != Guid.Empty)
      {
        using (var ctx = ContextManager<BusinessControl2DataContext>.GetManager(Database.BizControlDB))
        {
          if (IsSelfDirty)
          {
            Binary lastTimeStamp = null;
            LastChangedBy = new PersonInfo(SecurityChecks.GetCurrentUser());
            LastChanged = DateTime.Now;
            using (BypassPropertyChecks)
            {
              ctx.DataContext.UpdateBusinessRole(
                RoleId,
                Name,
                IsDeletedField,
                LastChanged,
                LastChangedBy == null || LastChangedBy.IsEmpty() ? (Guid?)null : LastChangedBy.Id,
                TimeStamp,
                ref lastTimeStamp);
              TimeStamp = lastTimeStamp.ToArray();
            }
          }
          // update child objects
          FieldManager.UpdateChildren(this);
        }
      }
    }

    [Transactional(TransactionalTypes.TransactionScope)]
    protected override void DataPortal_DeleteSelf()
    {
      DataPortal_Delete(new SingleCriteria<BusinessRoleBO, Guid>(RoleId));
    }

    [Transactional(TransactionalTypes.TransactionScope)]
    private void DataPortal_Delete(SingleCriteria<BusinessRoleBO, Guid> criteria)
    {
      IsDeletedField = true;
      DataPortal_Update();
    }

    #endregion

    #region Factory Methods

    private BusinessRoleBO()
    { /* require use of factory methods */ }

    public static BusinessRoleBO NewBusinessRole(ModelBO model)
    {
      return Csla.DataPortal.Create<BusinessRoleBO>(model);
    }

    public static BusinessRoleBO GetBusinessRole(Guid id)
    {
      return Csla.DataPortal.Fetch<BusinessRoleBO>(new SingleCriteria<BusinessRoleBO, Guid>(id));
    }

    public static BusinessRoleBO NewBusinessRole()
    {
      var model = SecurityChecks.GetCurrentModel();
      return Csla.DataPortal.Create<BusinessRoleBO>(model);
    }

    private static BusinessRoleBO _emptyRole;
    public static BusinessRoleBO GetEmptyRole()
    {
      if (_emptyRole == null)
      {
        _emptyRole = new BusinessRoleBO();
        _emptyRole.RoleId = Guid.Empty;
        _emptyRole.Name = PropertiesNames.EmptyName;
      }
      return _emptyRole;
    }

    #endregion

    #region ISupportEmtpyValue Members

    public bool IsEmpty()
    {
      return RoleId == Guid.Empty;
    }

    #endregion
  }
}
